//
//  HUFaceManager.m
//  YY键盘
//
//  Created by hu on 16/5/30.
//  Copyright © 2016年 hu. All rights reserved.
//
#import "HUFaceManager.h"
#import "YYText.h"
@interface HUFaceManager()


@end
@implementation HUFaceManager
- (instancetype)init{
    if (self = [super init]) {
        _emojiFaceArrays = [NSMutableArray array];
        
        NSArray *faceArray = [NSArray arrayWithContentsOfFile:[HUFaceManager defaultEmojiFacePath]];
        [_emojiFaceArrays addObjectsFromArray:faceArray];
        
        NSArray *recentArrays = [[NSUserDefaults standardUserDefaults] arrayForKey:@"recentFaceArrays"];
        if (recentArrays) {
            _recentFaceArrays = [NSMutableArray arrayWithArray:recentArrays];
        }else{
            _recentFaceArrays = [NSMutableArray array];
        }
        
    }
    return self;
}


#pragma mark - Class Methods

+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    static id shareInstance;
    dispatch_once(&onceToken, ^{
        shareInstance = [[self alloc] init];
    });
    return shareInstance;
}


#pragma mark - Emoji相关表情处理方法

+ (NSArray *)emojiFaces{
    return [[HUFaceManager shareInstance] emojiFaceArrays];
}


+ (NSString *)defaultEmojiFacePath{
    return [[NSBundle mainBundle] pathForResource:@"face" ofType:@"plist"];
}

+ (NSString *)faceImageNameWithFaceID:(NSUInteger)faceID{
    if (faceID == 999) {
        return @"[删除]";
    }
    for (NSDictionary *faceDict in [[HUFaceManager shareInstance] emojiFaceArrays]) {
        if ([faceDict[kFaceIDKey] integerValue] == faceID) {
            return faceDict[kFaceImageNameKey];
        }
    }
    return @"";
}

+ (NSString *)faceNameWithFaceID:(NSUInteger)faceID{
    if (faceID == 999) {
        return @"[删除]";
    }
    for (NSDictionary *faceDict in [[HUFaceManager shareInstance] emojiFaceArrays]) {
        if ([faceDict[kFaceIDKey] integerValue] == faceID) {
            return faceDict[kFaceNameKey];
        }
    }
    return @"";
}

#pragma mark 文字转表情图片
+ (NSMutableAttributedString *)emotionStrWithString:(NSString *)text URLBlock:(URLBlock)URLBlock
{
    //1、创建一个可变的属性字符串
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
    //2、通过正则表达式来匹配字符串
    NSString *regex_emoji = @"\\[[a-zA-Z0-9\\/\\u4e00-\\u9fa5]+\\]"; //匹配表情
    
    NSError *error = nil;
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:regex_emoji options:NSRegularExpressionCaseInsensitive error:&error];
    if (!re) {
        NSLog(@"%@", [error localizedDescription]);
        return attributeString;
    }
    
    NSArray *resultArray = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    //3、获取所有的表情以及位置
    //用来存放字典，字典中存储的是图片和图片对应的位置
    NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:resultArray.count];
    //根据匹配范围来用图片进行相应的替换
    for(NSTextCheckingResult *match in resultArray) {
        //获取数组元素中得到range
        NSRange range = [match range];
        //获取原字符串中对应的值
        NSString *subStr = [text substringWithRange:range];
        
        for (NSDictionary *dict in [[HUFaceManager shareInstance] emojiFaceArrays]) {
            if ([dict[kFaceNameKey]  isEqualToString:subStr]) {
                //face[i][@"png"]就是我们要加载的图片
                //新建文字附件来存放我们的图片,iOS7才新加的对象
                NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
                //给附件添加图片
                textAttachment.image = [UIImage imageNamed:dict[kFaceImageNameKey]];
                //调整一下图片的位置,如果你的图片偏上或者偏下，调整一下bounds的y值即可
                textAttachment.bounds = CGRectMake(0, -8, textAttachment.image.size.width, textAttachment.image.size.height);
                
                //把图片和图片对应的位置存入字典中
                NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];
                [imageDic setObject:textAttachment.image forKey:@"image"];
                [imageDic setObject:[NSValue valueWithRange:range] forKey:@"range"];
                //把字典存入数组中
                [imageArray addObject:imageDic];
                break;
            }
        }
    }
    
    //4、从后往前替换，否则会引起位置问题
    for (int i = (int)imageArray.count -1; i >= 0; i--) {
        NSRange range;
        [imageArray[i][@"range"] getValue:&range];
        //进行替换
        
        UIImage *image = imageArray[i][@"image"];
        
        
        image = [UIImage imageWithCGImage:image.CGImage scale:2 orientation:UIImageOrientationUp];
        NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:[UIFont systemFontOfSize:12] alignment:YYTextVerticalAlignmentCenter];
        [attributeString replaceCharactersInRange:range withAttributedString:attachText];
    }
    attributeString = [HUFaceManager getHttpURLFromString:attributeString URLBlock:^(NSString *content, NSUInteger type) {
        if (URLBlock) URLBlock(content,type);
    }];
    return attributeString;
}

#pragma mark 识别URL 
+ (NSMutableAttributedString *)getHttpURLFromString:(NSMutableAttributedString *)text URLBlock:(URLBlock)URLBlock{
   
    
//    NSMutableAttributedString* attributed = [[NSMutableAttributedString alloc]initWithString:text];
    
    NSArray* array = [HUFaceManager getHttpURLArrayFromString:text.string];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString* str = (NSString *)obj;
        NSRange range = [text.string rangeOfString:str];
        [HUFaceManager httpURL:text withRange:range URLBlock:^(NSString *content, NSUInteger type) {
            if (URLBlock) URLBlock(content,type);
        }];
    }];
    return text;
    
}
+ (NSArray *) getHttpURLArrayFromString:(NSString *) str {
    
    NSError* error = nil;
    //        NSString* regulaStr = @"(\\w+)://([^/:]+)(:\\d*)?([^#\\s]*)";
    NSString* regulaStr = @"(^(((ht|f)tp(s?))\\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\\-\\.]+\\.(com|cn|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\\\,\\;\\?\\'\\\\+&amp;%\\$#\\=~_\\-]+))*$)|((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|((((http[s]{0,1}|ftp)://)?((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))(\\:[0-9]+)(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    NSArray *arrayOfAllMatches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
    NSMutableArray* numbers = [NSMutableArray arrayWithCapacity:arrayOfAllMatches.count];
    for (NSTextCheckingResult *match in arrayOfAllMatches)
    {
        NSString* substringForMatch = [str substringWithRange:match.range];
        [numbers addObject:substringForMatch];
        
    }
    
    return numbers;
}
#pragma mark 修改连接文本在这里
+ (NSAttributedString *)httpURL:(NSMutableAttributedString *)text withRange:(NSRange)range URLBlock:(URLBlock)URLBlock{
    NSMutableAttributedString *one = text;
    one.yy_font = [UIFont systemFontOfSize:16];
    
    [one yy_setTextHighlightRange:range
                            color:[UIColor colorWithRed:0.093 green:0.492 blue:1.000 alpha:1.000]
                  backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220]
                        tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                            NSString* string = [text.string substringWithRange:range];
                            URLBlock(string,0);
                        }];
    
    return one;
}
#pragma mark - 最近使用表情相关方法
/**
 *  获取最近使用的表情图片
 *
 *  @return
 */
+ (NSArray *)recentFaces{
    return [[HUFaceManager shareInstance] recentFaceArrays];
}


+ (BOOL)saveRecentFace:(NSDictionary *)recentDict{
    for (NSDictionary *dict in [[HUFaceManager shareInstance] recentFaceArrays]) {
        if ([dict[@"face_id"] integerValue] == [recentDict[@"face_id"] integerValue]) {
            return NO;
        }
    }
    [[[HUFaceManager shareInstance] recentFaceArrays] insertObject:recentDict atIndex:0];
    if ([[HUFaceManager shareInstance] recentFaceArrays].count > 8) {
        [[[HUFaceManager shareInstance] recentFaceArrays] removeLastObject];
    }
    [[NSUserDefaults standardUserDefaults] setObject:[[HUFaceManager shareInstance] recentFaceArrays] forKey:@"recentFaceArrays"];
    return YES;
}


@end
